package mornd.test1;



import org.apache.tomcat.jni.Error;
import org.springframework.cglib.core.DebuggingClassWriter;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.io.IOException;
import java.lang.reflect.Method;
import java.rmi.AccessException;

/**
 * @author: mornd
 * @dateTime: 2023/5/5 - 19:06
 * jdk 动态代理有限制，只能针对接口代理，cglib 没有这些限制
 */
public class Demo {
    public static void main(String[] ar) throws Exception {
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "E:\\idea_work_space2023\\springSourceCode\\_07_cglibProxy\\src\\main\\java\\mornd\\test1\\cglib$classes");

        A a = new B();
        B proxyA = (B) Enhancer.create(a.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("before");

                //Object r = method.invoke(a, objects);

                /**
                 * methodProxy 可以避免通过反射调用目标方法
                 */
                //Object r= methodProxy.invoke(a, objects); // spring 使用的就是这种，需要目标对象

                Object r= methodProxy.invokeSuper(o, objects); // 可以避免反射，不需要目标对象，代理替换目标
                System.out.println("after");
                return r;
            }
        });
        proxyA.func("");

        System.out.println(proxyA.getClass());
        System.in.read();
    }

    static interface A {
        int func(String name);
    }

    static class B implements A {

        public int func(String name) {
            System.out.println("B func()-" + name);
            return 1;
        }
    }
}
